package demo1;


import java.util.*;

public class Task {
    public static void main(String[] args) {
        String str = "";
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        str = scan.nextLine();
        recordAppearMostFrequently(str);
    }

    public static void recordAppearMostFrequently(String str) {
        Map<Character, Integer> map = new HashMap<>();    //设置一个map集合用来存储字符和字符出现的次数的集合
        int count = 0;                                    //count用来单个字符出现的次数
        int[] sum = new int[str.length()];                //sum用来记录所有的字符出现的次数

        for (int i = 0; i < str.length(); i++) {
            for (int j = 0; j < str.length(); j++) {
                if (str.charAt(i) == str.charAt(j))
                    count++;
            }
            sum[i] = count;
            count = 0;
        }

        int maxIndex = maxIndexOfArray(sum);               //求到出现次数最多的那个值的下标
        map.put(str.charAt(maxIndex), sum[maxIndex]);      //存入map集合
        for (int i = 0; i < sum.length; i++) {
            //判断条件
            if (sum[i] == sum[maxIndex] && str.charAt(i) != str.charAt(maxIndex)) {
                map.put(str.charAt(i), sum[i]);
            }
        }

        System.out.print("出现次数最多的字符是");

        keySet(map);
        System.out.println("出现了" + map.get(str.charAt(maxIndex)) + "次.");
    }

    //遍历数组
    public static void printArray(int[] array) {
        for (int i : array)
            System.out.print(i + " ");
        System.out.println();
    }

    public static void keySet(Map<Character, Integer> map) {
        //1.获取存储了所有的键的集合
        Set<Character> keys = map.keySet();
        //2.遍历整个Set集合
        for (Character key : keys) {
            //2.1通过键获取值
            int value = map.get(key);
            //System.out.print("'"+key+"'"+",");
            System.out.println("key=" + key + ",value=" + value);
            // System.out.println("key="+key);
        }
    }

    //求最大值的下标
    public static int maxIndexOfArray(int[] array) {
        int max = Integer.MIN_VALUE;
        int maxIndex = 0;
        for (int i = 0; i < array.length; i++) {
            if (max < array[i]) {
                max = array[i];
                maxIndex = i;
            }
        }
        return maxIndex;
    }
}
